import Vue from "vue";
import VueRouter from "vue-router";
import login from "../views/login.vue";
import layout from "../views/layout.vue";
import users from "../views/users";
import roles from "../views/rights/roles.vue";
import rights from "../views/rights/rights.vue";
import goods from "../views/goods/goods.vue";
import params from "../views/goods/params.vue";
import goodsAdd from "../views/goods/goodsAdd.vue";
import categories from "../views/goods/categories.vue";
import orders from "../views/orders";
import reports from "../views/reports";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    name: "login",
    component: login
  },
  {
    path: "/",
    name: "layout",
    component: layout,
    redirect: "/users",
    children: [
      { path: "/users", component: users },
      { path: "/roles", component: roles },
      { path: "/rights", component: rights },
      { path: "/goods", component: goods },
      { path: "/params", component: params },
      { path: "/categories", component: categories },
      { path: "/goods/add", component: goodsAdd },
      { path: "/orders", component: orders },
      { path: "/reports", component: reports }
    ]
  }
];

const router = new VueRouter({
  routes
});
//导航守卫
router.beforeEach((to, from, next) => {
  NProgress.start();
  const user = localStorage.getItem("HEIMA_SHOP_USER");
  if (user && to.path === "/login") next("/");
  const whiteList = ["/login"];
  if (whiteList.includes(to.path)) {
    next();
  } else {
    if (user) {
      next();
    } else {
      next("/login?url=" + to.path);
    }
  }
});
router.afterEach((to, from) => {
  NProgress.done();
});
export default router;
